package com.choudou5.solr.web.handler.sys;

import com.choudou5.solr.utils.DingTalkUtil;
import com.choudou5.solr.annotation.ReqMapping;
import com.choudou5.solr.annotation.ReqMethod;
import com.choudou5.solr.bean.client.SolrClientAuth;
import com.choudou5.solr.bean.common.PageResult;
import com.choudou5.solr.bean.common.SqlQueryBean;
import com.choudou5.solr.bean.sys.SysDictBean;
import com.choudou5.solr.framework.constants.DictConsts;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.util.PageJumpUtil;
import com.choudou5.solr.framework.util.RequestUtil;
import com.choudou5.solr.service.ServiceHelper;
import com.choudou5.solr.service.client.SolrClientAuthService;
import com.choudou5.solr.service.sys.SysDictService;
import com.choudou5.solr.util.AssertUtil;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.util.SysSeqUtil;
import com.choudou5.solr.utils.SqlQueryBuilder;
import com.choudou5.solr.web.handler.BaseHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @name 管理员处理
 * @author choudou5
 * @date 2018-08-06
 */
public class SuperAdminHandler extends BaseHandler {

    private SysDictService sysDictService = ServiceHelper.singleton(SysDictService.class);
    private SolrClientAuthService clientAuthService = ServiceHelper.singleton(SolrClientAuthService.class);

    @Override
    public void execute(String method, HttpServletRequest req, HttpServletResponse resp) {
        logger.info("SuperAdminHandler method:{}", method);
        if(isSuperAdmin(req, resp)){
            switch (method){
                case "console":
                    console(req, resp);
                    break;
                case "setDebug":
                    setDebug(req, resp);
                    break;
                case "setAdminMail":
                    setAdminMail(req, resp);
                    break;
                case "apiAppList":
                    apiAppList(req, resp);
                    break;
                case "getApiAppKey":
                    getApiAppKey(req, resp);
                    break;
                case "updateApiAppConfig":
                    updateApiAppConfig(req, resp);
                    break;
                case "clearApiAppCache":
                    clearApiAppCache(req, resp);
                    break;
                case "setDingTalkGroup":
                    setDingTalkGroup(req, resp);
                    break;
                case "testDingTalk":
                    testDingTalk(req, resp);
                    break;
                default:
                    PageJumpUtil.errorOut(ErrorResp.Not_Found, req, resp);
                    break;
            }
        }
    }

    private void console(HttpServletRequest req, HttpServletResponse resp){
        PageJumpUtil.forward("adminConsole", req, resp);
    }

    @ReqMapping(desc = "设置管理员邮箱", method = ReqMethod.POST)
    private void setAdminMail(HttpServletRequest req, HttpServletResponse resp){
        String mail = RequestUtil.getStrParameter(req, "adminMail");
        if(!StrUtil.isEmail(mail)){
            PageJumpUtil.writeJsonInvalidParam("请输入有效邮箱", resp);
            return;
        }
        sysDictService.updateDictVal("管理员邮箱", DictConsts.ADMIN_MAIL, mail);
        PageJumpUtil.writeJsonOk("更新成功", resp);
    }

    @ReqMapping(desc = "设置调试", method = ReqMethod.POST)
    private void setDebug(HttpServletRequest req, HttpServletResponse resp){
        boolean isOpenDebug = RequestUtil.getBoolParameter(req, "isOpenDebug", false);
        req.getSession().getServletContext().setAttribute("__OPEN_DEBUG", isOpenDebug);
        PageJumpUtil.writeJsonOk("设置成功，刷新页面即生效", resp);
    }


    @ReqMapping(desc = "设置钉钉群组", method = ReqMethod.POST)
    private void setDingTalkGroup(HttpServletRequest req, HttpServletResponse resp){
        String groupType = RequestUtil.getStrParameter(req, "groupType");
        String chatId = RequestUtil.getStrParameter(req, "chatId");
        if(validParam(req, resp, new Object[]{groupType, chatId}, new String[]{"参数groupType", "参数chatId"})){
            sysDictService.updateDictVal("钉钉群组", groupType, chatId);
            if("ding_admin_group".equals(groupType)){
                DingTalkUtil.setAdminGroupId(chatId);
            }else if("ding_ops_group".equals(groupType)){
                DingTalkUtil.setOpsGroupId(chatId);
            }
            PageJumpUtil.writeJsonOk("更新成功", resp);
        }
    }

    @ReqMapping(desc = "测试发送钉钉群组消息", method = ReqMethod.POST)
    private void testDingTalk(HttpServletRequest req, HttpServletResponse resp){
        String groupType = RequestUtil.getStrParameter(req, "groupType");
        String message = RequestUtil.getStrParameter(req, "message");
        if(validParam(req, resp, new Object[]{groupType, message}, new String[]{"参数groupType", "参数message"})){
            SysDictBean bean = sysDictService.getByDictType(groupType);
            AssertUtil.isNotNull(bean, "群组无效");
            DingTalkUtil.sendTextMsg(bean.getDictValue(), message);
            PageJumpUtil.writeJsonOk("发送成功", resp);
        }
    }


    /**
     * API 应用列表
     * @param req
     * @param resp
     */
    private void apiAppList(HttpServletRequest req, HttpServletResponse resp){
        SqlQueryBean sqlQueryBean = SqlQueryBuilder.buildWhereSql(req);
        sqlQueryBean.setOrderDefParam("create_time", "DESC");
        PageResult<SolrClientAuth> pageResult = clientAuthService.findPage(sqlQueryBean);
        req.setAttribute("pageResult", pageResult);
        PageJumpUtil.forward("apiAppList", req, resp);
    }

    private void getApiAppKey(HttpServletRequest req, HttpServletResponse resp){
        String idStr = RequestUtil.getStrParameter(req, "id");
        Integer id = SysSeqUtil.decryptIntId(idStr);
        if(id==null){
            PageJumpUtil.writeJsonInvalidParam("请求参数无效，请联系管理员", resp);
            return;
        }
        String appKey = clientAuthService.getAppKey(id);
        PageJumpUtil.writeJsonObjOk(appKey, resp);
    }

    @ReqMapping(desc = "更新Api应用配置", method = ReqMethod.POST)
    private void updateApiAppConfig(HttpServletRequest req, HttpServletResponse resp){
        String idStr = RequestUtil.getStrParameter(req, "id");
        Integer id = SysSeqUtil.decryptIntId(idStr);
        if(id==null){
            PageJumpUtil.writeJsonInvalidParam("请求参数无效，请联系管理员", resp);
            return;
        }
        String appKey = RequestUtil.getStrParameter(req, "appKey");
        String whiteIp = RequestUtil.getStrParameter(req, "whiteIp");
        String authApi = RequestUtil.getStrParameter(req, "authApi");
        String status = RequestUtil.getStrParameter(req, "status");
        String remarks = RequestUtil.getStrParameter(req, "remarks");
        SolrClientAuth apiAppBean = new SolrClientAuth(id, appKey, whiteIp, authApi, remarks, status);
        clientAuthService.update(apiAppBean);
        PageJumpUtil.writeJsonOk("更新成功", resp);
    }

    private void clearApiAppCache(HttpServletRequest req, HttpServletResponse resp){
        String key = RequestUtil.getStrParameter(req, "key");
        key = SysSeqUtil.decryptId(key);
        if(key==null){
            PageJumpUtil.writeJsonInvalidParam("请求参数无效，请联系管理员", resp);
            return;
        }
        clientAuthService.removeCache(key);
        PageJumpUtil.writeJsonObjOk("清理完成", resp);
    }

}
